package saves.objects;

import game.Units;
import images.ObjectLoader;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.World;
import saves.Area;
import saves.EntidadeNave;

/**
 *
 * @author u11173
 */
public class Explosao {
    private static final long serialVersionUID = 1L;

    private float x, y, power;
    private long stime, time;
    
    private Body[] particles;
    
    private EntidadeNave owner;

    public Explosao(float x, float y, float power, long time, EntidadeNave owner) {
        this.x = x;
        this.y = y;
        this.power = power;
        this.time = this.stime = time;
    }
    
    public void setParticles(Body[] b) {
        this.particles = b;
    }
    
    public void destroyParticles(World w) {
        for (int i = 0; particles != null && i < particles.length; i++)
            w.destroyBody(particles[i]);
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }

    public float getPower() {
        return power;
    }

    public EntidadeNave getOwner() {
        return owner;
    }
    
    public boolean update(int delta, Area a) {
        this.time -= delta;
        if (this.time <= 0)
            return true;
        if (power < 0) { //implosion
            for (Corpo m : a.getObjetos()) {
                if (m.body.getType() != BodyType.DYNAMIC) //do not affect kinematic bodies anyway
                    continue;
                float dist = (float) m.dist(x, y);
                if (dist <= 10000) {
                    Vec2 dir = new Vec2(x, y).sub(new Vec2(m.getRealX(), m.getRealY()));
                    dir.normalize();
                    dir = dir.mul(-100*power/(dist*dist));
                    if (time == stime - delta)
                        return false; //first tick, test todo
                    m.body.applyForceToCenter(dir);
                }
            }
        }
        return false;
    }
    
    public void draw(float dx, float dy) {
        //draw background
        final int s = 64;
        if (power >= 0)
            ObjectLoader.drawExplosion((int) (10 * (float) (stime - time)/stime), (int) (Units.getPixelSize(x) - dx) - s/2, (int) (Units.getPixelSize(y) - dy) - s/2, s);
        else
            ObjectLoader.drawImplosion((int) (11 * (float) (stime - time)/stime), (int) (Units.getPixelSize(x) - dx) - s/2, (int) (Units.getPixelSize(y) - dy) - s/2, s);
        
        //draw particles
        if (particles != null)
            for (Body b : particles) {
                int ox = Units.getPixelSize(b.getPosition().x) - (int) dx,
                    oy = Units.getPixelSize(b.getPosition().y) - (int) dy;
                ObjectLoader.drawExpParticle(ox, oy, ((float) Math.toDegrees(b.getAngle()) + 90) % 360);
            }
    }
}
